global FIRST_YEAR 1964
global FINAL_YEAR 2016
global dropbox_dir "C:\Users\yuxu\Dropbox\PROJECTS (ACTIVE)\Bond.Risk.Premia.Mitra.Xu\Data\PRIOR_TO_RFS_RR\"

/*
* 5a. Regressing yields on labor market variables, previous data
*/

freduse UNRATE, clear
gen datem = ym(year(daten),month(daten))
format datem %tm
keep datem UNRATE

merge 1:1 datem using "${dropbox_dir}combined_results_yu\data\HWI_barnichon.dta"
keep if _merge==3
drop _merge

merge 1:1 datem using "${dropbox_dir}combined_results_yu\data\unemp_flow_rates.dta"
keep if _merge==3
drop _merge

rename f f_flow
rename F f_prob

save temp.dta, replace

use "${dropbox_dir}combined_results_yu\data\fama_bliss_prices.dta", clear
gen D = mod(Date_yyyymmdd, 100)
gen M = mod((Date_yyyymmdd - D)/100, 100)
gen Y = (Date_yyyymmdd - 100*M - D)/10000
gen datem = ym(Y,M)
format datem %tm
keep datem price_*

merge 1:1 datem using temp.dta
keep if _merge==3
drop _merge

tsset datem

sleep 5000
erase temp.dta

forvalues n = 1/5{
    gen yld_`n'y = -100*log(price_`n'y/100)/`n'
}

forvalues n = 2/5{
    gen slope_`n'y_1y = yld_`n'y - yld_1y
	local nlag = `n'-1
	gen hpxr_`n'y = 100*(log(price_`nlag'y/100) - log(L12.price_`n'y/100) + log(L12.price_1y/100))
}

gen hpxr_ave = (hpxr_2y + hpxr_3y + hpxr_4y + hpxr_5y)/4

gen tightness = HWI/UNRATE

keep if datem>=ym(${FIRST_YEAR},1) & datem<=ym(${FINAL_YEAR},12)

local RHS_list tightness f_flow
local bond_list ave 2y 3y 4y 5y

local NEWEY_WEST_LAGS 12

foreach rhs of local RHS_list{
    estimates clear
    eststo clear
    foreach b of local bond_list{
	    qui reg hpxr_`b' L12.`rhs'
		local r2 = round(`e(r2)',.001)
		local Nobs = `e(N)'
		eststo: qui newey hpxr_`b' L12.`rhs', lag(`NEWEY_WEST_LAGS')
		qui estadd local r_squared "`r2'"
		qui estadd local num_obs "`Nobs'"
		estimates store model_`b'
	}
	esttab using "reg_hpxr_`rhs'_${FIRST_YEAR}_${FINAL_YEAR}.tex", replace scalars("num_obs N" "r_squared R2")
	esttab model_*, scalars("r_squared R2")
	eststo clear
}